package org.linlinjava.litemall.admin.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.linlinjava.litemall.admin.beans.vo.UserOptionVo;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallRechargeTransactions;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserVo;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.BeanUtil;
import org.linlinjava.litemall.db.util.CompletionDateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Maps;

/**
 * 用户服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Service
public class UserService {
    /**
     * litemall用户服务
     */
    @Autowired
    private LitemallUserService litemallUserService;

    /**
     * 查询用户统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return {@link Object}
     */
    public Object queryUserStatistics(Integer registerType,String startTime, String endTime) {
//        DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime startTimes = LocalDateTime.parse(startTime, timeDtf);
//        LocalDateTime endTimes = LocalDateTime.parse(endTime, timeDtf);

        //查询用户信息
        long  userTotal = litemallUserService.list(Wrappers.lambdaQuery(LitemallUser.class)
                .eq(registerType!=null,LitemallUser::getRegisterType,registerType)).size();
        Map<String, Object> map = Maps.newHashMap();
        //今日新增
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//当天零点
        map.put("userTodayCount", litemallUserService.list(Wrappers.lambdaQuery(LitemallUser.class)
            .eq(registerType!=null,LitemallUser::getRegisterType,registerType)
            .between(LitemallUser::getAddTime, todayStart, todayEnd)).size());
        //昨日新增
        LocalDateTime yesterdayStart = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN);
        LocalDateTime yesterdayEnd = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX);//当天零点
        map.put("userYesterdayCount", litemallUserService.list(Wrappers.lambdaQuery(LitemallUser.class)
             .eq(registerType!=null,LitemallUser::getRegisterType,registerType)
            .between(LitemallUser::getAddTime, yesterdayStart, yesterdayEnd)).size());
        //本月新增
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime firstday = LocalDateTime.of(localDateTime.with(TemporalAdjusters.firstDayOfMonth()).toLocalDate(), LocalTime.MIN);
        LocalDateTime lastDay = LocalDateTime.of(localDateTime.with(TemporalAdjusters.lastDayOfMonth()).toLocalDate(), LocalTime.MAX);
        map.put("userMonthCount", litemallUserService.list(Wrappers.lambdaQuery(LitemallUser.class)
             .eq(registerType!=null,LitemallUser::getRegisterType,registerType)
            .between(LitemallUser::getAddTime, firstday, lastDay)).size());
        //会员总数
        map.put("userTotal", userTotal);

        return ResponseUtil.ok(map);
    }

    /**
     * 查询添加用户统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return {@link Object}
     */
    public ResponseUtil.Response queryAddUserStatistics( String startTime, String endTime,Integer registerType) {

        DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        Map<String, Object> map = Maps.newHashMap();
        map.put("startTime", LocalDateTime.parse(startTime, timeDtf));
        map.put("endTime", LocalDateTime.parse(endTime, timeDtf));
        map.put("registerType", registerType);

        //获取日期
        List<Map<String, Object>> maps = litemallUserService.queryAddUserStatistics(map);
        //3.补全为空的日期
        //补全后的结果
        List<Map<String, Object>> result = new ArrayList<>();
        boolean dbDateExist = false;
        List<String> dateList = CompletionDateUtils.completionDate( LocalDateTime.parse(startTime, timeDtf),  LocalDateTime.parse(endTime, timeDtf));
        for (String date : dateList) {
            //table为数据库查询出来的对象列表，结构为List<Map<String, Object>>
            for (Map<String, Object> row : maps ) {
                if (date.equals(row.get("addTime"))) {
                    //集合已包含该日期
                    dbDateExist = true;
                    result.add(row);
                    break;
                }
            }
            //添加补全的数据到最后结果列表
            if (!dbDateExist) {
                Map<String, Object> temp = new HashMap<>(2);
                temp.put("addTime", date);
                temp.put("count", 0);
                result.add(temp);
            }
            //状态修改为不存在
            dbDateExist = false;
        }
        return ResponseUtil.ok(result);
    }


    public Object queryByKeywordNoInner(String keyword) {
        LambdaQueryWrapper<LitemallUser> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(keyword).ifPresent(val -> queryWrapper.eq(LitemallUser::getMobile, val));
        Optional.ofNullable(keyword).ifPresent(val -> queryWrapper.eq(LitemallUser::getUsername, val));
        Optional.ofNullable(keyword).ifPresent(val -> queryWrapper.eq(LitemallUser::getEmail, val));
        List<LitemallUser> userList = litemallUserService.list(queryWrapper);
        return BeanUtil.copyList(userList,LitemallUserVo.class);
    }
}
